package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SendDingDingTalkUtils {

    /**
     * 发送钉钉群消息，使用文本格式
     *
     * @param content         发送内容
     * @param dingDingTalkUrl 发送地址
     * @param autograph       密钥
     * @throws Exception
     */
    public static void sedDingDingTalk(String content, String autograph, String dingDingTalkUrl) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("content", content);
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "text");
        reqMap.put("text", map);
        JSONObject jsonObject = new JSONObject(reqMap);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        Response response = RestAssured.given().headers(headers).body(jsonObject).when().post(autograph(autograph, dingDingTalkUrl));
        log.info("钉钉消息推送结果：" + response.prettyPrint());

    }

    /**
     * 获取密钥地址
     *
     * @param autograph       密钥
     * @param dingDingTalkUrl 发送地址
     * @return 发货密钥地址
     * @throws Exception
     */
    public static String autograph(String autograph, String dingDingTalkUrl) throws Exception {
        Long timestamp = System.currentTimeMillis();
        String url = dingDingTalkUrl;
        url = url.concat("&timestamp=").concat(String.valueOf(timestamp));
        String stringToSign = timestamp + "\n" + autograph;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(autograph.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        url = url.concat("&sign=").concat(sign);
        log.info("钉钉密码签名后地址:{}", url);
        return url;
    }
}
